

import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import javax.imageio.stream.FileImageInputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;

import static com.itextpdf.text.pdf.codec.BmpImage.getImage;
import static javafx.application.Platform.exit;

/**
 * @author 余心乐sky
 * @create 2018-12-03 15:50
 **/
public class Main extends JFrame {
    //需要转换xls路径
    private String xlsPath;
    //照片文件夹路径
    private String photoDir;
    //导出PDF路径
    private String outputPDFPath;
    //导出PDF文件名
    private String  outputPDFName;
    // 主标题
    private String title;
    //专业
    private String major ;
    //等级
    private String level ;

    public void init() {


       this.setLayout(new BorderLayout());
        setTitle("生成PDF");
        setSize(300, 150);
        setLocationRelativeTo(null); // 窗口在屏幕中间显示
        setVisible(false);
        setLayout(new BorderLayout());


        xlsPath = selectXLSPath();
        if (xlsPath != null) {
            slectField(xlsPath);
        }

        /*
         *
         * 测试用的！！！
         * @author sky
         * @date 2018/12/4 11:19
         * @param []
         * @return void
         */
        /*xlsPath="F:\\pdf\\examOutput_kxt_hbmusic.xls";
        photoDir="F:\\pdf\\photo_kxt_yyxy";
        outputPDFPath ="F:\\pdf";
        outputPDFName ="output";
        title="2018年中音协音乐考级照片粘贴表";
        major="钢琴";
        level="十级";

        creatPDF(23);*/

    }

    /*
      界面选择xls
      return : xlsPath
     */
    private String selectXLSPath() {
        String path = null;
        JFileChooser jfc = new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        jfc.setFileFilter(new xmlFileFilter()); //对JFileChooser设置过滤器
        int value = jfc.showDialog(new JLabel(), "请选择xlm文件");
        if (value == JFileChooser.APPROVE_OPTION) {// 判断窗口是否点的是打开或保存
            File file = jfc.getSelectedFile();
            path = jfc.getSelectedFile().toString();
        } else {// 点了取消
            // do nothing
        }
        return path;
    }


    /*
      选择文件夹路径
      return : Path
     */
    private String selectDir(String string) {
        String path = null;
        JFileChooser jfc = new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//只能选择目录
        int value = jfc.showDialog(new JLabel(), string);
        if (value == JFileChooser.APPROVE_OPTION) {// 判断窗口是否点的是打开或保存
            //File file = jfc.getSelectedFile();
            path = jfc.getSelectedFile().toString();
        } else {// 点了取消
            // do nothing
        }
        return path;
    }

    /*
     *
     *
     * @author sky
     * @date 2018/12/3 16:28
     * @param xlsPath
     * @return
     */
    private void slectField(String filePath) {
        setVisible(true);
        JPanel jPanel = new JPanel();
        JPanel njPanel = new JPanel();
        JLabel text2 = new JLabel("请选择含有照片路径的一列");
        text2.setHorizontalAlignment(SwingConstants.CENTER);
        text2.setVerticalAlignment(SwingConstants.CENTER);
        njPanel.add(text2);
        add(njPanel, BorderLayout.NORTH);
        add(jPanel, BorderLayout.CENTER);
        // List<String> pathAddname = new ArrayList<>();
        JButton sure = new JButton("确定");

        // for (String filename : filelist) {
        Read read = new Read();
        read.openExcel(filePath);
        //System.out.println(filePath);
        //  String filepath=filelist.get(num);
        String[] names = new String[read.getColCount(0)];
        System.out.println(names);
        for (int i = 0; i < read.getColCount(0); i++) {
            names[i] = read.getCellContent(i, 0);
        }
        JComboBox fileone = new JComboBox(names);
        jPanel.add(fileone);
        jPanel.add(sure);
        //刷新页面
        jPanel.revalidate();
        sure.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int selectNum = -1;
                selectNum = fileone.getSelectedIndex();//选择项索引号
                if (selectNum == -1) {
                    JOptionPane.showMessageDialog(jPanel, "提示消息", "请选择照片列", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                photoDir = selectDir("请选择照片目录");

                title = JOptionPane.showInputDialog("请输入PDF标题");
                major = JOptionPane.showInputDialog("请输入专业名称");
                level = JOptionPane.showInputDialog("请输入等级");

                outputPDFPath = selectDir("请选择输出PDF路径");
                outputPDFName = JOptionPane.showInputDialog("请输入PDF文件名(可以为空，默认output)");
                if (outputPDFName.isEmpty()){
                    outputPDFName = "output";
                }


                //fileone.getSelectedItem();//选择项名称

                creatPDF(selectNum);
                JOptionPane.showMessageDialog(null, "导出成功，请到自定义目录查看PDF", "导出成功", JOptionPane.PLAIN_MESSAGE);
                System.exit(0);

            }
        });
    }

    private void creatPDF(int selectNum) {
        //设置姓名列
        int nameNum = 1;

        try {
            Workbook workbook = Workbook.getWorkbook(new File(xlsPath));
            Sheet[] sheet = workbook.getSheets();
            //默认读取第一个sheet
            Sheet s = sheet[0];
            // 得到行的总数 第一行是标题，切记切记！！
            int rowCount = s.getRows();
            int columnCount = s.getColumns(); // 得到列的总数
            String[][] fileXLs = new String[rowCount][columnCount];
            //将xls存入二维数组
            for (int i = 0; i < rowCount; i++) {
                for (int j = 0; j < columnCount; j++) {
                    Cell cell = s.getCell(j, i); // 第i行的第j列
                    cell.getContents();
                    fileXLs[i][j] = cell.getContents();
                }
            }
            //pdf需要的列数
            int needColumns = 2;

            Document doc = null;// 建立一个Document对象
            BaseFont baseCN = null;
            BaseFont baseEN = null;
            Font fontChinese = null;
            try {
                baseCN = BaseFont.createFont("C://Windows//Fonts//STZHONGS.TTF",
                        BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                baseEN = BaseFont.createFont("C://Windows//Fonts//times.ttf",
                        BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception(e);
            }
            doc = new Document(PageSize.A4);// 设置页面大小
            fontChinese = new Font(baseCN, 11, Font.NORMAL);
            try {
                PdfWriter.getInstance(doc,new FileOutputStream(outputPDFPath+"\\"+outputPDFName+".pdf"));
                doc.open();
                //主标题
                Font titleFont = new Font(baseCN, 20, Font.BOLD);
                Paragraph titlePara = new Paragraph(title, titleFont);
                titlePara.setAlignment(Element.ALIGN_CENTER);
                titlePara.setSpacingAfter(6);
                doc.add(titlePara);

               //小标题
                Font littleTitleFont = new Font(baseCN, 13, Font.BOLD);
                Paragraph littleTitlePara = new Paragraph("专业："+major+"    级别："+level, littleTitleFont);
                littleTitlePara.setAlignment(Element.ALIGN_CENTER);
                littleTitlePara.setSpacingAfter(6);
                doc.add(littleTitlePara);


                //照片和姓名
                for (int peopleNum = 1; peopleNum < rowCount;) {
                    //Image img = Image.getInstance(photoDir + "\\" +fileXLs[peopleNum][selectNum] );
                    //PdfPCell cel2 = new PdfPCell(new Phrase("姓名：" + fileXLs[peopleNum][nameNum] ));

                    PdfPTable table = new PdfPTable(5);
                    table.setTotalWidth(550);

                    table.setLockedWidth(true);
                    table.setHorizontalAlignment(Element.ALIGN_LEFT);


                    for(int i = 0; i < 5; i++) {
                        int newNum = i + peopleNum ;
                        if(newNum > rowCount-1 ){
                            //手动留出空白
                            PdfPCell cell1 = new PdfPCell(new Phrase("", fontChinese));
                            cell1.setColspan(1);
                            cell1.setBorder(0);   //隐藏边框
                            table.addCell(cell1);
                        }else {
                            PdfPCell celall = new PdfPCell();
                            celall.setPaddingTop(35);
                            celall.setBorder(0);

                            PdfPTable table1 = new PdfPTable(1);
                            table1.setTotalWidth(550);
                            table1.setLockedWidth(true);
                            table1.setHorizontalAlignment(Element.ALIGN_LEFT);

                            Image img = Image.getInstance(photoDir + "\\" +fileXLs[newNum][selectNum] );
                            img.scaleAbsolute(90, 120);
                            PdfPCell cel1 = new PdfPCell(img);
                            cel1.setHorizontalAlignment(Element.ALIGN_LEFT);
                            cel1.setVerticalAlignment(Element.ALIGN_LEFT);
                           // cel1.setRowspan(3);
                            cel1.setBorder(0);
                            table1.addCell(cel1);

                            //姓名
                            PdfPCell cel2 = new PdfPCell(new Phrase( "       "+fileXLs[newNum][nameNum] , fontChinese));
                            cel2.setHorizontalAlignment(Element.ALIGN_LEFT);
                            cel2.setVerticalAlignment(Element.ALIGN_MIDDLE);
                            cel2.setBorder(0);
                            cel2.setMinimumHeight(20);
                            table1.addCell(cel2);

                          /*
                           PdfPCell cell1 = new PdfPCell(new Phrase("数量：" + newNum, fontChinese));
                            //System.out.println(newNum);
                           // cell1.setBorder(0);
                            cell1.setColspan(1);
                            */
                            celall.addElement(table1);
                            table.addCell(celall);
                        }


                    }
                    doc.add(table);
                    peopleNum += 5;

                }
                doc.close();

            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            System.out.println(e.getCause());
        }
    }

}
